<template>
  <div class="p-2">
    <!-- Success Message View -->
    <el-card v-if="showSuccessMessage" shadow="hover" class="success-card">
      <el-result
        icon="success"
        title="已成功入住"
        :sub-title="`将在 ${countdown} 秒后自动返回列表页`"
      >
        <template #extra>
           <el-progress type="circle" :percentage="countdownPercentage" :width="80">
             <span style="font-size: 24px;">{{ countdown }}</span>
           </el-progress>
           <div style="margin-top: 20px;">
             <el-button type="primary" @click="handleReturnToList">立即返回列表</el-button>
           </div>
        </template>
      </el-result>
    </el-card>

    <!-- Main Admission Process View (Hide when success message is shown) -->
    <el-card v-else shadow="hover">
      <template #header>
        <div class="card-header">
          <span>客户入住流程</span>
          <div class="right-buttons">
            <el-button v-if="activeStep > 0" type="primary" plain @click="prevStep">上一步</el-button>
            <el-button v-if="activeStep < steps.length - 1" type="primary" @click="nextStep">下一步</el-button>
            <el-button v-if="activeStep === steps.length - 1" type="success" @click="submitForm">提交</el-button>
            <el-button @click="cancel">取消</el-button>
          </div>
        </div>
      </template>
      
      <!-- 步骤条 -->
      <el-steps :active="activeStep" finish-status="success" class="mb-4">
        <el-step v-for="(step, index) in steps" :key="index" :title="step.title" :description="step.description" />
      </el-steps>
      
      <!-- 步骤内容区域 -->
      <div class="step-content">
        <!-- 步骤1：基本信息 -->
        <div v-show="activeStep === 0">
          <el-row :gutter="20" class="mb-4">
            <el-col :span="24">
              <el-radio-group v-model="elderSelectType" @change="handleElderSelectTypeChange">
                <el-radio :label="'existing'">选择已有老人</el-radio>
                <el-radio :label="'new'">添加新老人</el-radio>
              </el-radio-group>
            </el-col>
          </el-row>
          
          <!-- 选择已有老人 -->
          <div v-if="elderSelectType === 'existing'">
            <el-row :gutter="20" class="mb-4">
              <el-col :span="18">
                <el-input
                  v-model="elderSearchKeyword"
                  placeholder="输入老人姓名或身份证号搜索"
                  clearable
                  @keyup.enter="searchElder"
                >
                  <template #append>
                    <el-button @click="searchElder">
                      <el-icon><search /></el-icon>
                    </el-button>
                  </template>
                </el-input>
              </el-col>
              <el-col :span="6">
                <el-button type="primary" @click="searchElder">搜索</el-button>
              </el-col>
            </el-row>
            
            <el-table
              v-loading="elderLoading"
              :data="elderList"
              border
              highlight-current-row
              @row-click="handleElderSelect"
              style="width: 100%"
            >
              <el-table-column type="index" width="50" />
              <el-table-column label="姓名" prop="elderName" min-width="100" />
              <el-table-column label="性别" prop="gender" min-width="60">
                <template #default="scope">
                  {{ scope.row.gender === 1 ? '男' : '女' }}
                </template>
              </el-table-column>
              <el-table-column label="身份证号" prop="idCard" min-width="150" />
              <el-table-column label="年龄" prop="age" min-width="60" />
              <el-table-column label="联系电话" prop="phone" min-width="120" />
              <el-table-column label="操作" width="100">
                <template #default="scope">
                  <el-button link type="primary" @click.stop="handleElderSelect(scope.row)">选择</el-button>
                </template>
              </el-table-column>
            </el-table>
            
            <el-pagination
              v-if="elderList.length > 0"
              class="mt-2"
              layout="total, sizes, prev, pager, next"
              :total="elderTotal"
              :page-size="elderQuery.pageSize"
              :current-page="elderQuery.pageNum"
              @size-change="handleElderSizeChange"
              @current-change="handleElderCurrentChange"
            />
          </div>
          
          <!-- 添加新老人 -->
          <el-form
            v-else
            ref="basicInfoFormRef"
            :model="formData"
            :rules="rules.basicInfo"
            label-width="120px"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="老人照片" prop="elderPhoto">
                  <image-upload v-model="formData.elderPhoto"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="老人姓名" prop="elderName">
                  <el-input v-model="formData.elderName" placeholder="请输入老人姓名" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="性别" prop="gender">
                  <el-select v-model="formData.gender" placeholder="请选择性别" style="width: 100%">
                    <el-option label="男" :value="1" />
                    <el-option label="女" :value="0" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="出生日期" prop="birthDate">
                  <el-date-picker
                    v-model="formData.birthDate"
                    type="date"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="请选择出生日期"
                    style="width: 100%"
                    @change="calculateAge"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="年龄" prop="age">
                  <el-input-number v-model="formData.age" :min="0" :max="150" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="证件类型" prop="idCardType">
                  <el-select v-model="formData.idCardType" placeholder="请选择证件类型" style="width: 100%">
                    <el-option label="身份证" :value="1" />
                    <el-option label="护照" :value="2" />
                    <el-option label="其他" :value="3" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="证件号码" prop="idCard">
                  <el-input v-model="formData.idCard" placeholder="请输入证件号码" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="联系电话" prop="phone">
                  <el-input v-model="formData.phone" placeholder="请输入联系电话" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="家庭地址" prop="addressDetail">
                  <el-input v-model="formData.addressDetail" placeholder="请输入家庭地址" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="健康状况" prop="healthStatus">
                  <el-input v-model="formData.healthStatus" type="textarea" placeholder="请简述健康状况" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          
          <!-- 已选老人信息卡片 -->
          <el-card v-if="elderSelectType === 'existing' && selectedElder" class="mt-4">
            <template #header>
              <div class="card-header">
                <span>已选老人信息</span>
                <el-button link type="danger" @click="clearSelectedElder">取消选择</el-button>
              </div>
            </template>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="姓名">{{ selectedElder.elderName }}</el-descriptions-item>
              <el-descriptions-item label="性别">{{ selectedElder.gender === '1' ? '男' : (selectedElder.gender === '0' ? '女' : '未知') }}</el-descriptions-item>
              <el-descriptions-item label="身份证号">{{ selectedElder.idCard }}</el-descriptions-item>
              <el-descriptions-item label="年龄">{{ selectedElder.age }}</el-descriptions-item>
              <el-descriptions-item label="家庭地址" :span="2">{{ selectedElder.address || '未填写' }}</el-descriptions-item>
            </el-descriptions>
          </el-card>
        </div>
        
        <!-- 步骤2：联系人信息 -->
        <div v-show="activeStep === 1">
          <el-form ref="contactInfoFormRef" :model="formData" :rules="rules.contactInfo" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="联系人姓名" prop="contactName">
                  <el-input v-model="formData.contactName" placeholder="请输入联系人姓名" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系人电话" prop="contactPhone">
                  <el-input v-model="formData.contactPhone" placeholder="请输入联系人电话" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="与老人关系" prop="relationship">
                  <el-select v-model="formData.relationship" placeholder="请选择关系" style="width: 100%">
                    <el-option label="子女" value="子女" />
                    <el-option label="配偶" value="配偶" />
                    <el-option label="兄弟姐妹" value="兄弟姐妹" />
                    <el-option label="其他亲属" value="其他亲属" />
                    <el-option label="朋友" value="朋友" />
                    <el-option label="其他" value="其他" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系人地址" prop="contactAddress">
                  <el-input v-model="formData.contactAddress" placeholder="请输入联系人地址" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        
        <!-- 步骤3：入住信息 -->
        <div v-show="activeStep === 2">
          <el-form ref="admissionInfoFormRef" :model="formData" :rules="rules.admissionInfo" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="合同编号" prop="contractNo">
                  <el-input v-model="formData.contractNo" placeholder="请输入合同编号" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="入住日期" prop="startDate">
                  <el-date-picker
                    v-model="formData.startDate"
                    type="date"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="请选择入住日期"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="预计结束日期" prop="endDate">
                  <el-date-picker
                    v-model="formData.endDate"
                    type="date"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    placeholder="请选择预计结束日期"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同类型" prop="contractType">
                  <el-select v-model="formData.contractType" placeholder="请选择合同类型" style="width: 100%">
                    <el-option v-for="dict in sys_contract_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="房间号" prop="roomId">
                  <el-select 
                    v-model="formData.roomId" 
                    placeholder="请选择房间号" 
                    style="width: 100%"
                    @change="handleRoomChange"
                    :loading="roomLoading"
                  >
                    <el-option 
                      v-for="room in roomList" 
                      :key="room.roomId" 
                      :label="room.roomNo + ' (' + room.roomType + ')'" 
                      :value="room.roomId" 
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="床位号" prop="bedNo">
                  <el-select 
                    v-model="formData.bedNo" 
                    placeholder="请选择床位号" 
                    style="width: 100%"
                    :loading="bedLoading"
                    :disabled="!formData.roomId"
                  >
                    <el-option 
                      v-for="bed in bedList" 
                      :key="bed.bedId" 
                      :label="bed.bedNo" 
                      :value="bed.bedNo" 
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="月费用" prop="monthlyFee">
                  <el-input-number v-model="formData.monthlyFee" :min="0" :precision="2" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="押金" prop="deposit">
                  <el-input-number v-model="formData.deposit" :min="0" :precision="2" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="护理等级" prop="careLevel">
                  <el-select v-model="formData.careLevel" placeholder="请选择护理等级" style="width: 100%">
                    <el-option label="一级护理" value="一级护理" />
                    <el-option label="二级护理" value="二级护理" />
                    <el-option label="三级护理" value="三级护理" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="付款周期" prop="paymentCycle">
                  <el-select v-model="formData.paymentCycle" placeholder="请选择付款周期" style="width: 100%">
                    <el-option label="月付" value="月付" />
                    <el-option label="季付" value="季付" />
                    <el-option label="半年付" value="半年付" />
                    <el-option label="年付" value="年付" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        
        <!-- 步骤4：费用信息 -->
        <div v-show="activeStep === 3">
          <el-form ref="feeInfoFormRef" :model="formData" :rules="rules.feeInfo" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="费用类型" prop="feeType">
                  <el-select v-model="formData.feeType" placeholder="请选择费用类型" style="width: 100%">
                    <el-option label="住宿费" value="住宿费" />
                    <el-option label="护理费" value="护理费" />
                    <el-option label="餐饮费" value="餐饮费" />
                    <el-option label="押金" value="押金" />
                    <el-option label="其他费用" value="其他费用" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="金额" prop="amount">
                  <el-input-number v-model="formData.amount" :min="0" :precision="2" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="支付方式" prop="paymentMethod">
                  <el-select v-model="formData.paymentMethod" placeholder="请选择支付方式" style="width: 100%">
                    <el-option label="现金" value="现金" />
                    <el-option label="微信" value="微信" />
                    <el-option label="支付宝" value="支付宝" />
                    <el-option label="银行转账" value="银行转账" />
                    <el-option label="其他" value="其他" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="支付状态" prop="paymentStatus">
                  <el-select v-model="formData.paymentStatus" placeholder="请选择支付状态" style="width: 100%">
                    <el-option label="已支付" value="已支付" />
                    <el-option label="未支付" value="未支付" />
                    <el-option label="部分支付" value="部分支付" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        
        <!-- 步骤5：确认信息 -->
        <div v-show="activeStep === 4">
          <el-descriptions title="入住信息确认" :column="2" border>
            <el-descriptions-item label="老人姓名">{{ formData.elderName }}</el-descriptions-item>
            <el-descriptions-item label="性别">{{ formData.gender === 1 || formData.gender === '1' ? '男' : '女' }}</el-descriptions-item>
            <el-descriptions-item label="身份证号">{{ formData.idCard }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ formData.phone }}</el-descriptions-item>
            <el-descriptions-item label="联系人姓名">{{ formData.contactName }}</el-descriptions-item>
            <el-descriptions-item label="联系人电话">{{ formData.contactPhone }}</el-descriptions-item>
            <el-descriptions-item label="与老人关系">{{ formData.relationship }}</el-descriptions-item>
            <el-descriptions-item label="合同编号">{{ formData.contractNo }}</el-descriptions-item>
            <el-descriptions-item label="入住日期">{{ formatDisplayDate(formData.startDate) }}</el-descriptions-item>
            <el-descriptions-item label="预计结束日期">{{ formatDisplayDate(formData.endDate) }}</el-descriptions-item>
            <el-descriptions-item label="房间号">{{ formData.roomId }}</el-descriptions-item>
            <el-descriptions-item label="床位号">{{ formData.bedNo }}</el-descriptions-item>
            <el-descriptions-item label="护理等级">{{ formData.careLevel }}</el-descriptions-item>
            <el-descriptions-item label="费用类型">{{ formData.feeType }}</el-descriptions-item>
            <el-descriptions-item label="金额">{{ formData.amount }}</el-descriptions-item>
            <el-descriptions-item label="支付方式">{{ formData.paymentMethod }}</el-descriptions-item>
            <el-descriptions-item label="支付状态">{{ formData.paymentStatus }}</el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">{{ formData.remark }}</el-descriptions-item>
          </el-descriptions>
          
          <div class="mt-4">
            <el-checkbox v-model="formData.agreement">我已确认以上信息无误，并同意相关服务条款</el-checkbox>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup name="AdmissionProcess" lang="ts">
import { addAdmissionContract } from '@/api/nursing/admissionContract';
import { addFeeRecord } from '@/api/nursing/feeRecord';
import { listElder, getElder, addElder } from '@/api/nursing/elder';
import { getCurrentInstance, reactive, ref, computed, onMounted, onUnmounted, toRefs } from 'vue';
import type { ComponentInternalInstance } from 'vue';
import type { ElForm } from 'element-plus';
import type { ElderBasicVO, ElderBasicQuery, ElderForm } from '@/api/nursing/elder/types';
import type { AdmissionContractForm } from '@/api/nursing/admissionContract/types';
import { useRouter } from 'vue-router';

// 使用路由
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_contract_type } = toRefs<any>(proxy?.useDict('sys_contract_type'));

// State for success message and countdown
const showSuccessMessage = ref(false);
const countdown = ref(5);
let intervalId: number | null = null;

// 步骤条配置
const steps = [
  { title: '基本信息', description: '老人的基本信息' },
  { title: '联系人信息', description: '紧急联系人信息' },
  { title: '入住信息', description: '入住合同相关信息' },
  { title: '费用信息', description: '费用缴纳信息' },
  { title: '确认信息', description: '确认所有信息' }
];

// 当前激活的步骤
const activeStep = ref(0);

// 房间相关
// 临时定义RoomInfoVO和BedInfoVO接口，后续可以移到专门的类型文件中
interface RoomInfoVO {
  roomId: string | number;
  roomNo: string;
  roomType: string;
  price?: number;
  status?: string;
}

interface BedInfoVO {
  bedId: string | number;
  bedNo: string;
  roomId: string | number;
  status?: string;
}

const roomList = ref<RoomInfoVO[]>([]);
const roomLoading = ref(false);
const bedList = ref<BedInfoVO[]>([]);
const bedLoading = ref(false);

// 老人选择类型：existing=选择已有老人，new=添加新老人
const elderSelectType = ref('existing');
// 老人查询关键字
const elderSearchKeyword = ref('');
// 老人查询加载状态
const elderLoading = ref(false);
// 老人列表
const elderList = ref<ElderBasicVO[]>([]);
// 老人总数
const elderTotal = ref(0);
// 老人查询参数
const elderQuery = reactive<ElderBasicQuery>({
  pageNum: 1,
  pageSize: 10,
  elderName: undefined,
  idCard: undefined
});
// 已选择的老人
const selectedElder = ref<ElderBasicVO | null>(null);

// 表单引用
const basicInfoFormRef = ref<InstanceType<typeof ElForm>>();
const contactInfoFormRef = ref<InstanceType<typeof ElForm>>();
const admissionInfoFormRef = ref<InstanceType<typeof ElForm>>();
const feeInfoFormRef = ref<InstanceType<typeof ElForm>>();

// 表单数据
const formData = reactive({
  // 老人ID (仅当选择已有老人时使用)
  elderId: undefined,
  // 基本信息
  elderPhoto: '',
  elderName: '',
  gender: undefined,
  birthDate: '',
  age: undefined,
  idCardType: 1, // 默认为身份证
  idCard: '',
  phone: '',
  addressDetail: '',
  healthStatus: '',
  
  // 联系人信息
  contactName: '',
  contactPhone: '',
  relationship: '',
  contactAddress: '',
  
  // 入住信息
  contractNo: '',
  startDate: '',
  endDate: '',
  roomId: undefined,
  bedNo: '',
  careLevel: '',
  contractType: '',
  monthlyFee: undefined,
  deposit: undefined,
  paymentCycle: '', // 付款周期
  
  // 费用信息
  feeType: '',
  amount: 0,
  paymentMethod: '',
  paymentStatus: '',
  remark: '',
  
  // 确认信息
  agreement: false
});

// 表单验证规则
const rules = {
  basicInfo: {
    elderName: [{ required: true, message: '请输入老人姓名', trigger: 'blur' }],
    idCard: [{ required: true, message: '请输入身份证号', trigger: 'blur' }],
  },
  contactInfo: {
  },
  admissionInfo: {
  },
  feeInfo: {
  }
};

// 根据出生日期计算年龄
const calculateAge = () => {
  if (formData.birthDate) {
    const birthDate = new Date(formData.birthDate);
    const today = new Date();
    let age = today.getFullYear() - birthDate.getFullYear();
    const monthDiff = today.getMonth() - birthDate.getMonth();
    
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
      age--;
    }
    
    formData.age = age;
  }
};

// 格式化日期显示
const formatDisplayDate = (date: any) => {
  if (!date) return '';
  
  // 如果是字符串且已经是标准格式，直接返回可读格式
  if (typeof date === 'string') {
    // 处理YYYY-MM-DD HH:mm:ss格式
    if (/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(date)) {
      return date.split(' ')[0]; // 只返回日期部分，不显示时间
    }
    return date;
  }
  
  // 如果是日期对象，转为标准格式
  try {
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  } catch (e) {
    console.error('日期格式化显示失败', e);
    return '';
  }
};

// 格式化日期为简单字符串 (用于API提交)
const formatSimpleDate = (date: any) => {
  if (!date) return '';
  if (typeof date === 'string') {
    if (/^\d{4}-\d{2}-\d{2}$/.test(date)) return date;
    return date.split('T')[0];
  }
  try {
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  } catch (e) {
    console.error('日期格式化失败', e);
    return '';
  }
};

// 老人选择类型变更处理
const handleElderSelectTypeChange = (value: string) => {
  if (value === 'existing') {
    // 清空新增老人表单
    if (!selectedElder.value) {
      resetBasicForm();
    }
    // 加载老人列表
    searchElder();
  } else {
    // 清除已选老人
    selectedElder.value = null;
    // 重置老人ID
    formData.elderId = undefined;
  }
};

// 搜索老人
const searchElder = async () => {
  elderLoading.value = true;
  // 设置搜索条件
  if (elderSearchKeyword.value) {
    // 根据关键字判断是身份证还是姓名
    if (/^\d+$/.test(elderSearchKeyword.value)) {
      elderQuery.idCard = elderSearchKeyword.value;
      elderQuery.elderName = undefined;
    } else {
      elderQuery.elderName = elderSearchKeyword.value;
      elderQuery.idCard = undefined;
    }
  } else {
    elderQuery.elderName = undefined;
    elderQuery.idCard = undefined;
  }
  
  try {
    const res = await listElder(elderQuery);
    elderList.value = res.rows;
    elderTotal.value = res.total;
  } catch (error) {
    console.error('获取老人列表失败', error);
    proxy?.$modal.msgError('获取老人列表失败');
  } finally {
    elderLoading.value = false;
  }
};

// 选择老人
const handleElderSelect = async (elder: ElderBasicVO) => {
  try {
    // 获取老人详情
    const res = await getElder(elder.elderId);
    // 安全的类型转换
    const elderData = res.data as any;
    
    // 设置选中的老人
    selectedElder.value = elder;
    
    // 将老人信息填入表单
    formData.elderId = elder.elderId;
    formData.elderName = elder.elderName;
    formData.gender = typeof elder.gender === 'string' ? (elder.gender === '1' ? 1 : 0) : elder.gender;
    formData.birthDate = elder.birthDate;
    formData.age = elder.age;
    
    // 如果从详情数据中有额外信息，也一并填入
    if (elderData) {
      formData.idCardType = elderData.idCardType || 1;
      formData.idCard = elder.idCard;
      formData.phone = elder.phoneNumber || '';
      formData.addressDetail = elderData.addressDetail || elder.address || '';
      formData.healthStatus = elderData.healthStatus || '';
      
      // 如果有联系人信息，也填入
      formData.contactName = elder.emergencyContact || '';
      formData.contactPhone = elder.emergencyPhone || '';
      formData.relationship = elder.relationship || '';
      formData.contactAddress = elderData.addressDetail || elder.address || '';
    }
    
    proxy?.$modal.msgSuccess('已选择老人: ' + elder.elderName);
  } catch (error) {
    console.error('获取老人详情失败', error);
    proxy?.$modal.msgError('获取老人详情失败');
  }
};

// 清除选中的老人
const clearSelectedElder = () => {
  selectedElder.value = null;
  formData.elderId = undefined;
  resetBasicForm();
};

// 重置基本信息表单
const resetBasicForm = () => {
  formData.elderName = '';
  formData.gender = undefined;
  formData.birthDate = '';
  formData.age = undefined;
  formData.idCardType = 1;
  formData.idCard = '';
  formData.phone = '';
  formData.addressDetail = '';
  formData.healthStatus = '';
};

// 分页大小变化
const handleElderSizeChange = (val: number) => {
  elderQuery.pageSize = val;
  searchElder();
};

// 分页页码变化
const handleElderCurrentChange = (val: number) => {
  elderQuery.pageNum = val;
  searchElder();
};

// 下一步
const nextStep = async () => {
  // 根据当前步骤进行表单验证
  let valid = false;
  
  switch (activeStep.value) {
    case 0: // 基本信息
      if (elderSelectType.value === 'existing') {
        // 已有老人，验证是否已选择
        if (selectedElder.value) {
          valid = true;
        } else {
          proxy?.$modal.msgError('请选择一个老人或切换到添加新老人');
        }
      } else {
        // 新老人，验证表单
      await basicInfoFormRef.value?.validate((isValid) => {
        valid = isValid;
      });
      }
      break;
    case 1: // 联系人信息
      await contactInfoFormRef.value?.validate((isValid) => {
        valid = isValid;
      });
      break;
    case 2: // 入住信息
      await admissionInfoFormRef.value?.validate((isValid) => {
        valid = isValid;
      });
      break;
    case 3: // 费用信息
      await feeInfoFormRef.value?.validate((isValid) => {
        valid = isValid;
      });
      break;
    default:
      valid = true;
  }
  
  if (valid) {
    activeStep.value++;
  }
};

// 上一步
const prevStep = () => {
  activeStep.value--;
};

// --- Countdown Logic --- 
const clearTimerAndNavigate = () => {
  if (intervalId) {
    clearInterval(intervalId);
    intervalId = null;
  }
  // Navigate back to the list page - 更新为实际有效的路径
  router.push('/check_in/admissionContract');
};

const startCountdown = () => {
  countdown.value = 5; // Reset countdown to 5 seconds
  showSuccessMessage.value = true; // Show the success view
  
  // Clear any existing timer
  if (intervalId) {
      clearInterval(intervalId);
  }

  intervalId = window.setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearTimerAndNavigate(); // Navigate when countdown reaches 0
    }
  }, 1000); // Decrease every second
};

// Handler for the manual return button
const handleReturnToList = () => {
  clearTimerAndNavigate();
};

// Computed property for progress percentage
const countdownPercentage = computed(() => {
  // Avoid division by zero and handle initial state
  if (countdown.value <= 0) return 0;
  return (countdown.value / 5) * 100;
});

// --- Form Submission --- 
const submitForm = async () => {
  if (!formData.agreement) {
    proxy?.$modal.msgError('请先同意服务条款');
    return;
  }
  
  // Final validation check if needed (though steps should handle it)
  // Perform API calls
  try {
    // 1. Add Elder if 'new' type
    if (elderSelectType.value === 'new') {
      const elderData: any = {
        elderName: formData.elderName,
        gender: formData.gender,
        birthDate: formData.birthDate,  // 日期已通过选择器格式化
        age: formData.age,
        idCardType: formData.idCardType,
        idCard: formData.idCard,
        addressDetail: formData.addressDetail,
        healthStatus: formData.healthStatus,
        isActive: 1, 
        phoneNumber: formData.phone, 
      };
      const elderRes = await addElder(elderData);
      formData.elderId = elderRes.data.elderId; // Get the new elderId
    }
    
    // Ensure elderId is set for the contract and fee records
    if (!formData.elderId) {
        proxy?.$modal.msgError('未能获取老人ID，无法提交合同和费用');
        return;
    }

    // 2. Add Admission Contract
    const contractData: any = {
      elderId: formData.elderId,
      elderPhoto: formData.elderPhoto,
      elderName: formData.elderName,
      contactName: formData.contactName,
      contractNo: formData.contractNo,
      startDate: formData.startDate,  // 日期已通过选择器格式化
      endDate: formData.endDate,      // 日期已通过选择器格式化
      roomId: formData.roomId,
      bedNo: formData.bedNo,
      contractType: formData.contractType,
      monthlyFee: formData.monthlyFee,
      deposit: formData.deposit,
      paymentMethod: formData.paymentMethod,
      paymentCycle: formData.paymentCycle,
      contractStatus: '有效',
      signerRelationship: formData.relationship
    };
    await addAdmissionContract(contractData);
    
    // 3. Add Fee Record
    const feeData = {
      elderId: formData.elderId,
      elderName: formData.elderName,
      feeType: formData.feeType,
      amount: formData.amount,
      paymentDate: new Date().toISOString().substring(0, 19).replace('T', ' '),  // 格式化为 YYYY-MM-DD HH:mm:ss
      paymentMethod: formData.paymentMethod,
      status: formData.paymentStatus,
      remarks: formData.remark
    };
    await addFeeRecord(feeData);
    
    // --- Show Success View instead of modal and immediate redirect --- 
    startCountdown(); 
    
  } catch (error) {
    console.error('提交失败', error);
    proxy?.$modal.msgError('提交失败，请重试');
    showSuccessMessage.value = false; // Ensure success view is hidden on error
  }
};

// 取消
const cancel = () => {
  // Clear timer if user cancels
  if (intervalId) {
      clearInterval(intervalId);
      intervalId = null;
  }
  showSuccessMessage.value = false; // Hide success message if visible
  console.log('取消并返回列表页');
  router.push('/check_in/admissionContract');
};

// 组件挂载时加载老人列表和房间列表
onMounted(() => {
  searchElder();
  loadRooms();
});

// --- Lifecycle Hook for Cleanup --- 
onUnmounted(() => {
  if (intervalId) {
    clearInterval(intervalId);
  }
});


// 加载房间列表 (Keep using mock data for now)
const loadRooms = async () => {
  try {
    roomLoading.value = true;
    setTimeout(() => {
      roomList.value = [
        { roomId: 1, roomNo: '101', roomType: '单人间', price: 2000 },
        { roomId: 2, roomNo: '102', roomType: '双人间', price: 1500 },
        { roomId: 3, roomNo: '201', roomType: '单人间', price: 2200 },
        { roomId: 4, roomNo: '202', roomType: '三人间', price: 1200 },
      ];
      roomLoading.value = false;
    }, 500);
  } catch (error) {
    console.error('获取房间列表失败', error);
    proxy?.$modal.msgError('获取房间列表失败');
  }
};

// 房间变更处理 (Keep using mock data for now)
const handleRoomChange = async (roomId: number) => {
  if (!roomId) {
    bedList.value = [];
    formData.bedNo = '';
    return;
  }
  
  try {
    bedLoading.value = true;
    setTimeout(() => {
      if (roomId === 1) {
        bedList.value = [{ bedId: 1, bedNo: '101-1', roomId: 1, status: '空闲' }];
      } else if (roomId === 2) {
        bedList.value = [
          { bedId: 2, bedNo: '102-1', roomId: 2, status: '空闲' },
          { bedId: 3, bedNo: '102-2', roomId: 2, status: '空闲' }
        ];
      } else if (roomId === 3) {
        bedList.value = [{ bedId: 4, bedNo: '201-1', roomId: 3, status: '空闲' }];
      } else if (roomId === 4) {
        bedList.value = [
          { bedId: 5, bedNo: '202-1', roomId: 4, status: '空闲' },
          { bedId: 6, bedNo: '202-2', roomId: 4, status: '空闲' },
          { bedId: 7, bedNo: '202-3', roomId: 4, status: '空闲' }
        ];
      }
      bedLoading.value = false;
    }, 500);
    
    const selectedRoom = roomList.value.find(room => room.roomId === roomId);
    if (selectedRoom) {
      formData.monthlyFee = selectedRoom.price || 0;
    }
  } catch (error) {
    console.error('获取床位列表失败', error);
    proxy?.$modal.msgError('获取床位列表失败');
  } finally {
    bedLoading.value = false;
  }
};
</script>

<style scoped>
.success-card {
  text-align: center;
  padding: 40px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.right-buttons {
  display: flex;
  gap: 10px;
}

.step-content {
  padding: 20px 0;
  min-height: 300px; /* Ensure content area has some height */
}
</style>
